using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace Voodoo.Sauce.Tools.AccessButton
{
	public class HidePanel : MonoBehaviour
	{
		public delegate void OnHideChangeState(bool appear);

		public static OnHideChangeState HideChangeState;

		public CanvasGroup canvasGroup;

		public Image background;

		public RectTransform logo;

		private bool _visible;

		private const float LogoOnY = 0f;

		private const float LogoOffY = -256f;

		private const float LogoSpeedAppear = 20f;

		private const float BackgroundOn = 0.39f;

		private const float BackgroundOff = 0f;

		private const float BackgroundSpeedAppear = 0.02f;

		private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

		private void Start()
		{
			background.color = new Color(background.color.r, background.color.g, background.color.b, 0f);
			logo.localPosition = new Vector3(0f, -256f, 0f);
			HideChangeState = (OnHideChangeState)Delegate.Combine(HideChangeState, new OnHideChangeState(ChangeState));
			GroupVisibility(show: false);
		}

		private void ChangeState(bool appear)
		{
			_cancellationTokenSource = new CancellationTokenSource();
			UIDisappear();
			if (appear)
			{
				if (!_visible)
				{
					UIAppear();
				}
			}
			else if (_cancellationTokenSource != null && _cancellationTokenSource.Token.CanBeCanceled)
			{
				_cancellationTokenSource.Cancel();
			}
		}

		private async void UIAppear()
		{
			GroupVisibility(show: true);
			while ((background.color.a < 0.39f || logo.localPosition.y < 0f) && !_cancellationTokenSource.IsCancellationRequested)
			{
				if (background.color.a < 0.39f)
				{
					float a = background.color.a;
					background.color = new Color(background.color.r, background.color.g, background.color.b, a + 0.02f);
				}
				if (logo.localPosition.y < 0f)
				{
					logo.localPosition += new Vector3(0f, 20f, 0f);
				}
				await Task.Delay(25);
			}
			if (_cancellationTokenSource.IsCancellationRequested)
			{
				UIDisappear();
				_cancellationTokenSource = new CancellationTokenSource();
			}
			else
			{
				_visible = true;
			}
		}

		private void UIDisappear()
		{
			GroupVisibility(show: false);
			background.color = new Color(background.color.r, background.color.g, background.color.b, 0f);
			Vector3 localPosition = logo.localPosition;
			logo.localPosition = new Vector3(localPosition.x, -256f, localPosition.z);
			_visible = false;
		}

		private void OnDestroy()
		{
			_cancellationTokenSource.Dispose();
			HideChangeState = (OnHideChangeState)Delegate.Remove(HideChangeState, new OnHideChangeState(ChangeState));
		}

		private void GroupVisibility(bool show)
		{
			canvasGroup.interactable = show;
			canvasGroup.alpha = (show ? 1f : 0f);
		}
	}
}
